package cs131.pa1.filter.sequential;

import cs131.pa1.filter.Filter;
import cs131.pa1.filter.Message;

import java.io.File;
import java.util.List;

public class CdCommand extends SequentialFilter {
    public final static String COMMAND = "cd";
    public String workingDirectory;

    private String path;

    private List<String> commands;

    public CdCommand(String s) {
        this.path = s;
    }

    public CdCommand(List<String> commands) {
        this.commands=commands;
    }

    public void process() {
        if(commands.size()<2) {
            System.out.print(cs131.pa1.filter.Message.REQUIRES_PARAMETER.with_parameter(COMMAND));
            return;
        }
        path=commands.get(1);
        if (".".equals(path)) {
            return;
        }
        if ("..".equals(path)) {
            File file = new File(SequentialREPL.currentWorkingDirectory);
            SequentialREPL.currentWorkingDirectory = file.getParent();
            return;
        }
        if (path.startsWith(FILE_SEPARATOR)) {
            workingDirectory = path;
        } else {
            workingDirectory = SequentialREPL.currentWorkingDirectory + FILE_SEPARATOR + path;
        }
        changeDirectory(workingDirectory);
    }

    private void changeDirectory(String targetDirectorey) {
        File file = new File(targetDirectorey);
        if (!file.exists() || file.isFile()) {
            System.out.print(cs131.pa1.filter.Message.DIRECTORY_NOT_FOUND.with_parameter(COMMAND+ " "+ path));
        } else {
            SequentialREPL.currentWorkingDirectory = targetDirectorey;
        }
    }

    @Override
    protected String processLine(String line) {
        return null;
    }
}
